Textarea appends new content by jQuery

文章目录
  1. Abstract
    1. How to read file’s new content
    2. Textarea appends new content by jQuery

Abstract

Sometimes, we need implement a function that how we can read new content from a file and append to textarea in the html.In this article, I will write how to do it and show the new content from a file real-time in html.At last, making textarea more useful by jQuery.

How to read file’s new content

How to read file’s new content, about this features, we can read the issues at Reading file’s new content by Java. And we can implement the features in JavaEE project by SpringMVC or others. If we do it, programming can access a url interface to read a file’s new content, and return it.

Textarea appends new content by jQuery

How weak and powerless the words are, so there is html code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<html>
<head>
<script type="text/javascript" src="/assets/js/jquery-1.12.4.min.js"></script>
</head>
<body>
<div style="overflow: hidden; width:96%; display: block; position: absolute; top:80px; bottom: 0px;">
<textarea id="content" name="content" style="background-color: black; color: white; height:100%;"
placeholder="content" readonly="readonly"></textarea>
</div>
</body>
<script>
$(function () {
// reading file's new content per second
setInterval(function() {
getLog();
}, 1000);
});
// reading file
function getLog() {
$.ajax({
type: "GET",
async: false,
url: "/content",
dataType: "json", // return json data
success: function (data) {
if(data.result != "" && data.result != undefined) {
var clientHeight = $("#content")[0].clientHeight;
var scrollTop = $("#content")[0].scrollTop;
var scrollHeight = $("#content")[0].scrollHeight;
// append new content
$("#content").html($("#content").html() + data.result);
// only when the scroll bar at the bottom, keeping the scroll bar at the bottom
if(clientHeight + scrollTop >= scrollHeight) {
var scrollTop = $("#log")[0].scrollHeight;
$("#content").scrollTop(scrollTop);
} else {
$("#content").scrollTop(scrollTop);
}
}
},
error: function (errorMsg) {
// error tips
}
})
}
</script>
</html>

In the html code, program will read file’s new content per second by ajax request. And ajax will request an interface that url is /content, the Java interface will return a json data at last. So, textarea can appends new content by jQuery.
At last, although program can read the new content from a file and append content to textarea, textarea will keeping content at top every times. So in the code, we make textarea more useful by controlling the textarea only when the scroll bar at the bottom, keeping the scroll bar at the bottom.